package main

import (
	"flag"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/zeromicro/go-zero/rest/httpx"
	"imooc.com/easy-chat/pkg/resultx"
	"log"

	"imooc.com/easy-chat/apps/user/api/internal/config"
	"imooc.com/easy-chat/apps/user/api/internal/handler"
	"imooc.com/easy-chat/apps/user/api/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/dev/user.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	clientConfig := vo.NacosClientParam{
		ClientConfig: &constant.ClientConfig{
			NamespaceId: c.Nacos.NamespaceId,
			TimeoutMs:   5000,
		},
		ServerConfigs: []constant.ServerConfig{
			{IpAddr: c.Nacos.Host, Port: c.Nacos.Port},
		},
	}
	client, err := clients.NewNamingClient(clientConfig)
	if err != nil {
		panic(err)
	}
	// 注册服务实例
	_, err = client.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          c.Host,
		Port:        uint64(c.Port),
		ServiceName: c.Nacos.ServiceName,
		Weight:      10,
		ClusterName: "DEFAULT",
		GroupName:   c.Nacos.GroupName,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
	if err != nil {
		log.Fatal("Register service error:", err)
	}
	subErr := client.Subscribe(&vo.SubscribeParam{
		ServiceName: c.Nacos.ServiceName,
		GroupName:   c.Nacos.GroupName,
		SubscribeCallback: func(services []model.Instance, err error) {
			// 更新本地实例缓存
			log.Println(services)

		},
	})
	if subErr != nil {
		log.Fatal("sub service error:", err)
	}

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	httpx.SetErrorHandlerCtx(resultx.ErrHandler(c.Name))
	httpx.SetOkHandler(resultx.OkHandler)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)

	defer func() {
		// 4. 服务关闭时注销实例
		deregisterParam := vo.DeregisterInstanceParam{
			ServiceName: c.Nacos.ServiceName,
			GroupName:   c.Nacos.GroupName,
			Ip:          c.Host,
			Port:        uint64(c.Port),
		}
		if _, err := client.DeregisterInstance(deregisterParam); err != nil {
			log.Fatal("注销失败: " + err.Error())
		}
	}()

	server.Start()
}
